// 此页面用于微信小程序页面数据处理
const { Service } = require('egg');

class WxpageService extends Service {
  // 首页获取最新的商品
  // 参数 query 查询项，根据第几页，从第几条获取数据
  async getNewGoodsList(query) {
    try {
      let currentPage = parseInt(query.currentPage);
      let pageSize = parseInt(query.pageSize);
      let offset = (currentPage - 1) * pageSize;
      console.log(currentPage, pageSize, offset);
      return await this.app.model.Goods.findAndCountAll({
        order: [
          [ 'createdAt', 'DESC' ]
        ],
        offset,
        limit: pageSize
      });
    } catch (error) {
      return false;
    }
  }

  // 首页获取商品按销量排行
  async getSellGoodsList(query) {
    try {
      let currentPage = parseInt(query.currentPage);
      let pageSize = parseInt(query.pageSize);
      let offset = (currentPage - 1) * pageSize;
      console.log(currentPage, pageSize, offset);
      return await this.app.model.Goods.findAndCountAll({
        order: [
          [ 'goods_sell_num', 'DESC' ]
        ],
        offset,
        limit: pageSize
      });
    } catch (error) {
      return false;
    }
  }

  // 综合商品列表
  async getGoodsAllList(query) {
    try {
      let currentPage = parseInt(query.currentPage);
      let pageSize = parseInt(query.pageSize);
      let offset = (currentPage - 1) * pageSize;
      console.log(currentPage, pageSize, offset);
      return await this.app.model.Goods.findAndCountAll({
        order: [
          [ 'goods_name' ]
        ],
        offset,
        limit: pageSize
      });
    } catch (error) {
      return false;
    }
  }

  // 销量列表
  async getGoodsSalesList(query) {
    try {
      let currentPage = parseInt(query.currentPage);
      let pageSize = parseInt(query.pageSize);
      let offset = (currentPage - 1) * pageSize;
      console.log(currentPage, pageSize, offset);
      return await this.app.model.Goods.findAndCountAll({
        order: [
          [ 'goods_sell_num', 'DESC' ]
        ],
        offset,
        limit: pageSize
      });
    } catch (error) {
      return false;
    }
  }

  // 新品
  async getGoodsNewList(query) {
    try {
      let currentPage = parseInt(query.currentPage);
      let pageSize = parseInt(query.pageSize);
      let offset = (currentPage - 1) * pageSize;
      console.log(currentPage, pageSize, offset);
      return await this.app.model.Goods.findAndCountAll({
        order: [
          [ 'createdAt', 'DESC' ]
        ],
        offset,
        limit: pageSize
      });
    } catch (error) {
      return false;
    }
  }

  // 价格
  async getGoodsPriceList(query) {
    try {
      let currentPage = parseInt(query.currentPage);
      let pageSize = parseInt(query.pageSize);
      let offset = (currentPage - 1) * pageSize;
      console.log(currentPage, pageSize, offset);
      return await this.app.model.Goods.findAndCountAll({
        order: [
          [ 'goods_price', 'DESC' ]
        ],
        offset,
        limit: pageSize
      });
    } catch (error) {
      return false;
    }
  }

  // 推荐
  async getRecommendGoodsList() {
    try {
      let data = await this.app.model.Goods.findAll({
        attributes: [ 'id', 'goods_name', 'goods_price', 'goods_img' ],
        order: [
          [ 'createdAt', 'DESC' ]
        ]
      });
      // 数据长度
      let dataNum = data.length;
      let newArr = [];
      for (let i = 0; i < 4; i++) {
        let random = Math.floor(Math.random() * dataNum);
        // console.log(random);
        if (newArr.indexOf(data[random].dataValues) === -1) {
          newArr.push(data[random].dataValues);
        }
      }
      console.log(newArr.length);
      return newArr;
    } catch (e) {
      return false;
    }

  }

  // 获取单个商品
  async getOneGoodsInfo(id) {
    return await this.ctx.service.goods.getOne(id);
  }

  // 微信登录************************************************************************
  async wxLogin(userData) {
      let { openId } = userData;
      // 先判断是否存在此openid
      let data = await this.app.model.Wxuser.findOne(
        { where: { open_id: openId } }
      );
      // 有则取消添加，无则添加此用户
      if (data) {
        // 生成token，这里admin名字就按照后台用吧
        let user_jwt = { admin: openId };
        const token = this.app.jwt.sign(user_jwt, this.app.config.jwt.secret);
        return { state: true, result: token, userId: data.id };
      } else {
        // 添加
        await this.app.model.Wxuser.create({ open_id: openId });
        let user_jwt = { admin: openId };
        const token = this.app.jwt.sign(user_jwt, this.app.config.jwt.secret);
        // 获取服务器的用户id
        let current = await this.app.model.Wxuser.findOne(
          { where: { open_id: openId } }
        );
        return { state: true, result: token, userId: current.id };
      }
  }
  // 生成订单
  async createOrder(data) {
    try {
      let { buyList, userId, payAll, isPay, userInfo } = data;
      // 生成订单号
      // 此订单号数据库起始值100000000，然后获取+1来生成新的订单号
      // 获取最新的订单号
      let orderArr = await this.app.model.OrderNumber.findAll({
        order: [
          [ 'createdAt', 'DESC' ]
        ]
      });
      let startNumber = orderArr[0].number;
      let currentOrderNumber = startNumber + 1;
      await this.app.model.OrderNumber.create({ number: currentOrderNumber });
      // 生成订单
      // 判断用户是否付款，是则存1，否则存0
      if (isPay === true) {
        isPay = 1;
      } else {
        isPay = 0;
      }
      await this.app.model.Order.create({
        order_number: currentOrderNumber,
        order_price: payAll,
        order_userName: userInfo.userName,
        order_userTel: userInfo.userTel,
        order_address: userInfo.userAddr,
        user_id: userId,
        order_isSend: 0,
        order_isPay: isPay,
        order_isConfirm: 0
      });
      // 获取最新订单的id
      let orderList = await this.app.model.Order.findAll({
        order: [
          [ 'createdAt', 'DESC' ]
        ]
      });
      let currentOrderId = orderList[0].id;
      // 存储商品数据
      buyList.forEach( async item => {
        await this.app.model.UserGoods.create({
          goods_name: item.goods_name,
          goods_price: item.goods_price,
          goods_img: item.goods_img,
          num: item.num,
          goods_id: item.id,
          pay: item.pay,
          order_id: currentOrderId
        });
      });
      return true;
    } catch (err) {
      return false;
    }
  }
  // 用户订单列表
  // 参数 query，包含用户ID和分类index
  async getOrderList(query) {
    try {
      let userId = parseInt(query.id);
      let index = parseInt(query.index);
      const that = this.app;
      // 封装一个完整的订单列表方法
      async function getCurrentOrderList(userId, index) {
        let orderList = [];
        // 获取当前用户的所有订单
        // 判断用户是否付款 1默认所有订单，2待付款，3待发货，4待收货
        if (index === 1) {
          orderList = await that.model.Order.findAll({
            attributes: [ 'id', 'order_price', 'createdAt' ],
            where: {
              user_id: userId,
            },
            order: [
              [ 'updatedAt', 'DESC' ]
            ]
          });
        } else if (index === 2 || index === 3) {
          index = index - 2;
          console.log('当前的index==='+index);
          orderList = await that.model.Order.findAll({
            attributes: [ 'id', 'order_price', 'createdAt' ],
            where: {
              user_id: userId,
              order_isPay: index,
              order_isSend: 0
            },
            order: [
              [ 'createdAt', 'DESC' ]
            ]
          });
        } else if (index === 4) {
          console.log('当前的index==='+index);
          orderList = await that.model.Order.findAll({
            attributes: [ 'id', 'order_price', 'createdAt' ],
            where: {
              user_id: userId,
              order_isSend: 1,
              order_isConfirm: 0
            },
            order: [
              [ 'createdAt', 'DESC' ]
            ]
          });
        } else {
          return false;
        }
        return orderList;
      }
      let orderList = await getCurrentOrderList(userId, index);
      // 简化数据
      let newOrderList = [];
      orderList.forEach(item=>{
        newOrderList.push(item.dataValues);
      });
      // 保留订单ID
      let orderIDList = [];
      newOrderList.forEach(item=>{
        orderIDList.push(item.id);
      });
      // 根据订单ID找商品
      let arr = await this.app.model.UserGoods.findAll({
        attributes: [ 'id', 'goods_name', 'goods_price', 'goods_img', 'num', 'goods_id', 'order_id' ],
        where: {
          order_id: orderIDList
        }
      });
      // 简化数据
      let newGoodsList = [];
      arr.forEach(item=>{
        newGoodsList.push(item.dataValues);
      });
      // 生成数据[6,8]
      newOrderList.forEach(item=>{
        let currentId = item.id;
        let arr = newGoodsList.filter(i=>{
          return i.order_id === currentId;
        });
        item.children = arr;
      });
      return newOrderList;
    } catch (err) {
      return false;
    }

  }
  // 订单详情
  async getOrderDetail(id) {
    try {
      id = parseInt(id);
      // 找订单
      let data = await this.app.model.Order.findOne(
        { where: { id } }
      );
      // 找订单中的商品列表
      let list = await this.app.model.UserGoods.findAll(
        { where: { order_id:id } }
      );
      return {
        orderData: data,
        listData: list
      };
    } catch (error) {
      return false;
    }
  }
  // 修改收货状态为已收货
  async confirmOrder(id) {
    try {
      id = parseInt(id);
      await this.app.model.Order.update({ order_isConfirm: 1 }, {
        where: {
          id
        }
      });
      return true;
    } catch (error) {
      return false;
    }
  }
  // 再次付款修改付款状态
  async payOrder(id) {
    try {
      id = parseInt(id);
      await this.app.model.Order.update({ order_isPay: 1 }, {
        where: {
          id
        }
      });
      return true;
    } catch (error) {
      return false;
    }
  }
  // 删订单
  async deleteOrder(id) {
    try {
      id = parseInt(id);
      // 先删商品再删订单
      await this.app.model.UserGoods.destroy(
        { where: { order_id: id } }
      );
      await this.app.model.Order.destroy(
        { where: { id } }
      );
      return true;
    } catch (error) {
      return false;
    }
  }
}
module.exports = WxpageService;
